#include "weatherinfo.h"
#include <QDebug>
#include <QDate>
WeatherInfo::WeatherInfo(QObject *parent) : QObject(parent),
    m_pm25(0), m_pm10(0)
{
}

bool WeatherInfo::loadFromJson(const QString &json)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &error);

    if (error.error != QJsonParseError::NoError || !doc.isObject()) {
        qWarning() << "JSON parse error:" << error.errorString();
        return false;
    }

    QJsonObject root = doc.object();

    // 获取城市信息
    QJsonObject cityInfo = root["cityInfo"].toObject();
    m_city = cityInfo["city"].toString();
    m_updateTime = cityInfo["updateTime"].toString();

    // 获取日期
    m_date = root["date"].toString();

    // 获取天气数据
    QJsonObject data = root["data"].toObject();
    m_shidu = data["shidu"].toString();
    m_wendu = data["wendu"].toString();
    m_pm25 = data["pm25"].toDouble();
    m_pm10 = data["pm10"].toDouble();
    m_quality = data["quality"].toString();
    m_ganmao = data["ganmao"].toString();

    // 获取天气预报
    m_forecast.clear();
    QJsonArray forecastArray = data["forecast"].toArray();
    for (int i = 0; i < forecastArray.size() && i < 7; ++i) {
        QJsonObject obj = forecastArray[i].toObject();
        Forecast f;
        f.high = obj["high"].toString();
        f.low = obj["low"].toString();
        f.ymd = obj["ymd"].toString();
        f.week = obj["week"].toString();
        f.sunrise = obj["sunrise"].toString();
        f.sunset = obj["sunset"].toString();
        f.aqi = obj["aqi"].toInt();
        f.fx = obj["fx"].toString();
        f.fl = obj["fl"].toString();
        f.type = obj["type"].toString();
        f.notice = obj["notice"].toString();
        m_forecast.append(f);
    }

    return true;
}

bool WeatherInfo::isValid() const
{
    return !m_city.isEmpty() && !m_forecast.isEmpty();
}

QString WeatherInfo::city() const { return m_city; }
QString WeatherInfo::date() const { return m_date; }
QString WeatherInfo::formatteedDate() const
{
    QDate date = QDate::fromString(m_date , Qt::ISODate);
    if(!date.isValid())
    {
        date = QDate::fromString(m_date , "yyyy-MM-dd");
    }
    if(date.isValid())
    {
        return date.toString("yyyy/MM/dd");
    }
    return  m_date.length() >= 6? m_date.right(6):"01/01";
}
QString WeatherInfo::updateTime() const { return m_updateTime; }
QString WeatherInfo::shidu() const { return m_shidu; }
QString WeatherInfo::wendu() const { return m_wendu; }
double WeatherInfo::pm25() const { return m_pm25; }
double WeatherInfo::pm10() const { return m_pm10; }
QString WeatherInfo::quality() const { return m_quality; }
QString WeatherInfo::ganmao() const { return m_ganmao; }
QList<Forecast> WeatherInfo::forecastList() const { return m_forecast; }
